import { defineStore } from 'pinia';
import { localStorage, sessionStorage } from '@/utils/StorageUtils.ts';
import { useRouter } from "vue-router";
import { transformIcon } from "@/utils/VueUtils.ts";


/**
 * 获取菜单组件的树类列表
 */
const getMenus = (menus: ManageRule[]) => {
    const nm: MainMenu[] = [];
    menus.forEach((item: ManageRule) => {
        nm.push({
            label: item.title,
            key: item.code,
            p: item.pcode,
            icon: transformIcon(item.icon),
            breadcrumb: [item.title],
            path: item.path
        })
    })
    return menuTreeData(nm);
}

/**
 * 树结构
 * @param source
 */
const menuTreeData = (source: MainMenu[]) => {
    return source.filter((father: MainMenu) => {
        const branchArr = source.filter((child: MainMenu) => {
            if (father.key === child.p) {
                child.breadcrumb?.unshift(...(father.breadcrumb ?? []))
                return true;
            } else {
                return false;
            }
        })
        if (branchArr.length > 0) {
            father.children = branchArr;
        }
        return father.p === '0';
    })
}

const getRoutesByMenus = (menus: ManageRule[]) => {
    const router: objType = {};
    menus.forEach((item: ManageRule) => {
        router[item.code] = item.title;
    })
    return router;
}


export const useSystemStore = defineStore('system-store', {
    state: () => ({
        router: useRouter(),
        role: <ManageRole>{},
        admin: <ManageAdmin>{}, // 用户信息
        roleList: <ManageRole[]>[], // 角色列表
        menuData: <MainMenu[]>[], // 菜单数据
        tabData: <MainTab[]>[], // 标签页数据
        routes: <objType>{}, // 路由数据
        breadcrumb: <string[]>[], // 面包屑数据
        lastMenu: <MainMenu| null>{}, // 最后访问的菜单规则
    }),
    getters: {
        getMenuData(): MainMenu[] {
            const mainMenu = localStorage.get('system.menuData', this.menuData) as ManageRule[];
            this.menuData = getMenus(mainMenu);
            return this.menuData;
        },
        getTabData(): MainTab[] {
            this.tabData = localStorage.get('system.tabData', this.tabData) as MainTab[];
            return this.tabData;
        },
        getRoutes(): objType {
            return localStorage.get('system.routes', this.routes) as objType;
        },
        getBreadcrumb(): string[] {
            this.breadcrumb = localStorage.get('system.breadcrumb', this.breadcrumb) as string[];
            return this.breadcrumb;
        },
        getLastMenu(): MainMenu {
            this.lastMenu = localStorage.get('system.lastMenuRule', this.lastMenu) as MainMenu;
            return this.lastMenu;
        },
        getRole(): ManageRole {
            this.role = localStorage.get('system.role', this.role) as ManageRole;
            return this.role;
        },
        getAdmin(): ManageAdmin {
            this.admin = localStorage.get('system.admin', this.admin) as ManageAdmin;
            return this.admin;
        },
    },
    actions: {
        setMenuData(data: ManageRule[]) {
            // 将菜单数据转换为 MainMenu 类型
            localStorage.set('system.menuData', data);
            this.menuData = getMenus(data);
        },
        setTabData(data: MainTab[]) {
            localStorage.set('system.tabData', data);
            this.tabData = data;
        },
        setRoutes(data: ManageRule[]) {
            // 将路由数据转换为对象形式
            const routes = getRoutesByMenus(data);
            localStorage.set('system.routes', routes);
            this.routes = routes;
        },
        setLastMenu(data?: MainMenu) {
            if (data) {
                localStorage.set('system.lastMenuRule', data);
                this.lastMenu = data;
                // 更新面包屑
                this.setBreadcrumb(data.breadcrumb);
                // 跳转路径
                this.router.push(data.path);
            }else {
                localStorage.set('system.lastMenuRule', null);
                this.lastMenu = null;
                // 更新面包屑
                this.setBreadcrumb([]);
                // 跳转路径
                this.router.replace("/home").then(() => top?.location.reload());
            }
        },
        setBreadcrumb(data: string[]) {
            localStorage.set('system.breadcrumb', data);
            this.breadcrumb = data;
        },
        setRole(role: ManageRole) {
            localStorage.set('system.role', role);
            this.role = role;
        },
        setAdmin(admin: ManageAdmin) {
            localStorage.set('system.admin', admin);
            this.admin = admin;
        },
        setRoleList(roleList: ManageRole[]) {
            localStorage.set('system.roleList', roleList);
            this.roleList = roleList;
        },
        setLogin(token: string, admin: ManageAdmin, roleList: ManageRole[]) {
            this.setAdmin(admin);
            this.setRoleList(roleList);
            localStorage.set('system.token', token);
            sessionStorage.set('isLogin', 'true');
        },
        setLogout() {
            localStorage.clear();
            sessionStorage.clear();
            setTimeout(() => top?.location.reload() , 500);
        },
        goToHome() {
            this.setLastMenu();
        }
    }

})